//通用文件
const File = plus.android.importClass('java.io.File');
const SystemClock = plus.android.importClass('android.os.SystemClock');
export default {
	//自管理的状态数据
	state: {
		delayEvents: {} //延迟执行事件
	},
	//远程服务
	remoteServer: '39.100.7.70:5000',
	// remoteServer: '192.168.1.10:5000',
	//remoteServer: '192.168.6.101:5000',
	//remoteServer: '192.168.33.108:5000',
	//公共数据
	data: {
		timeIds: [], //定时器Ids
		newVersion: null, //新版本
		sysInfo: null, //系统信息
		hasMoreApply: null, //是否有更多的请求数据
		menuList: [{
				title: '发起群聊',
				icon: 'messagefill',
				code: 'group'
			},
			{
				title: '添加好友',
				icon: 'friendaddfill',
				code: 'add'
			},
			{
				title: '扫一扫',
				icon: 'scan',
				code: 'scan'
			}
		]
	},
	//头像文件夹
	avatarFolder: '_doc/Avatar/',
	//聊天文件夹
	chatFolder: '_doc/ChatFile/',
	//保存头像
	saveAvatar(sourceFile, newFileName) {
		return this.copyFile(sourceFile, this.avatarFolder, newFileName);
	},
	//获取头像路径
	getAvatar(fileName) {
		return this.avatarFolder + fileName;
	},
	//检查头像是否存在
	checkAvatar(data) {
		data = this.getAvatar(data);
		return this.checkFile(data);
	},
	//获取音频信息
	getAudioInfo(filePath) {
		return new Promise((res, rej) => {
			plus.io.getAudioInfo({
				filePath,
				success(data) {
					res(data);
				},
				fail(err) {
					console.log('音频信息获取失败', err);
					rej(err);
				}
			})
		});
	},
	//获取图片信息
	getImageInfo(filePath) {
		return new Promise((res, rej) => {
			uni.getImageInfo({
				src: filePath,
				success(data) {
					res(data);
				},
				fail(e) {
					console.log('图片信息获取失败', e);
					rej(e);
				}
			});
		});
	},
	//保存文件
	saveFile(filePath) {
		return new Promise((res, rej) => {
			uni.saveFile({
				tempFilePath: filePath,
				success(data) {
					res(data.savedFilePath);
				},
				fail(e) {
					console.log('文件保存失败', e);
					rej(e);
				}
			})
		});
	},
	//获取文件信息
	getFileInfo(filePath) {
		return new Promise((res, rej) => {
			uni.getFileInfo({
				filePath,
				success(e) {
					res(e);
				},
				fail() {
					rej();
				}
			})
		});
	},
	//创建文件夹
	createDir(path) {
		const destDir = new File(plus.io.convertLocalFileSystemURL(path));
		if (!destDir.exists()) {
			destDir.mkdirs();
		}
	},
	guid() {
		return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			var r = Math.random() * 16 | 0,
				v = c == 'x' ? r : (r & 0x3 | 0x8);
			return v.toString(16);
		});
	},
	//获取聊天文件
	getChatFile(filePath) {
		return this.chatFolder + filePath;
	},
	//保存聊天文件
	async saveChatFile(filePath) {
		let fileName = '';
		let count = 0;
		while (true) {
			fileName = this.guid() + '.' + filePath.split('.').pop();
			const exists = await this.checkFile(this.getChatFile(fileName));
			if (!exists) {
				break;
			}
			if (++count >= 3) {
				return Promise.reject('文件保存失败');
			}
		}
		await this.copyFile(filePath, this.chatFolder, fileName);
		return this.chatFolder + fileName;
	},
	//检查文件是否存在
	checkFile(filePath) {
		return new Promise((res, rej) => {
			uni.getFileInfo({
				filePath,
				success() {
					res(true);
				},
				fail() {
					res(false);
				}
			});
		});
	},
	//拷贝文件
	copyFile(sourceFile, desFolder, fileName) {
		return new Promise((res, rej) => {
			plus.io.resolveLocalFileSystemURL(sourceFile, fe => {
				plus.io.requestFileSystem(plus.io.PRIVATE_DOC, de => {
					de.root.getDirectory(desFolder, {
						create: true,
						exclusive: false
					}, de1 => {
						fe.copyTo(de1, fileName, e => {
							res(e);
						}, e => {
							rej(e);
							console.log('复制失败', e);
						});
					}, e => {
						console.log('获取目标目录失败', desFolder, e);
						rej(e);
					});
				}, e => {
					console.log('获取Doc目录失败', e);
					rej(e);
				});
			}, e => {
				console.log('获取源文件失败', sourceFile, e);
				rej(e);
			});
		});
	},
	//移动文件
	moveFile(sourceFile, desFolder, fileName) {
		return new Promise((res, rej) => {
			plus.io.resolveLocalFileSystemURL(sourceFile, fe => {
				plus.io.requestFileSystem(plus.io.PRIVATE_DOC, de => {
					de.root.getDirectory(desFolder, {
						create: true,
						exclusive: false
					}, de1 => {
						fe.moveTo(de1, fileName, e => {
							res(e);
						}, e => {
							rej(e);
							console.log('移动失败', e);
						});
					}, e => {
						console.log('获取目标目录失败', desFolder, e);
						rej(e);
					});
				}, e => {
					console.log('获取Doc目录失败', e);
					rej(e);
				});
			}, e => {
				console.log('获取源文件失败', sourceFile, e);
				rej(e);
			});
		});
	},
	//获取Store对象
	get store() {
		return uni.store;
	},
	// 获取更新中
	get updating() {
		return this.store.state.updating;
	},
	// 设置更新中
	set updating(data) {
		this.store.commit('setUpdating', data);
	},
	// 获取是否后台运行
	get runBehind() {
		return this.store.state.runBehind;
	},
	// 设置是否后台运行
	set runBehind(data) {
		if (this.store) {
			this.store.commit('setRunBehind', data);
		}
	},
	//根据范围获取随机数
	random(minNum, maxNum) {
		switch (arguments.length) {
			case 1:
				return parseInt(Math.random() * minNum + 1, 10);
				break;
			case 2:
				return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
				break;
			default:
				return 0;
				break;
		}
	},
	// 获取最大ID
	get maxId() {
		let id = this.store.state.maxId;
		this.maxId = ++id;
		return id;
	},
	// 设置最大ID
	set maxId(id) {
		this.store.commit('setMaxId', id);
	},
	//显示信息
	showToast(title, icon) {
		setTimeout(() => {
			uni.showToast({
				title,
				icon: icon || 'none'
			})
		});
	},
	// 获取令牌
	get token() {
		return this.store.state.token;
	},
	//设置令牌
	set token(token) {
		this.store.commit('setToken', token);
	},
	// 获取服务器时间
	get serverTime() {
		let serverTime = this.store.state.serverTime;
		let d = new Date(serverTime.time.getTime());
		let startTime = SystemClock.elapsedRealtime();
		d.setMilliseconds(startTime - serverTime.startTime);
		return d;
	},
	//服务器时间
	set serverTime(time) {
		time = this.parseDate(time, false);
		let startTime = SystemClock.elapsedRealtime();
		this.store.commit('setServerTime', {
			time,
			startTime
		});
	},
	// 获取群组
	get groups() {
		return this.store.state.groups;
	},
	//设置群组
	set groups(data) {
		this.store.commit('setGroups', data);
	},
	//获取好友
	get friends() {
		let fIds = this.store.state.friends;
		return this.users.filter(c => fIds.includes(c.Id));
	},
	//设置好友
	set friends(data) {
		this.store.commit('setFriends', data);
	},
	//获取所有用户
	get users() {
		return this.store.state.users;
	},
	//设置所有用户
	set users(data) {
		this.store.commit('setUsers', data);
	},
	//映射群组成员
	mappingGroupMembers(data) {
		if (undefined == data || null == data) {
			return;
		}
		this.users = data; //先将所有用户添加
		let users = this.users;
		if (Array.isArray(data)) {
			for (let i = 0; i < data.length; i++) {
				data[i] = users.find(c => c.Id == data[i].Id);
			}
		} else {
			let id = typeof data === 'number' ? data : data.Id; //用户ID
			return users.find(c => c.Id == id);
		}
	},
	//获取最新消息
	get newMessage() {
		return this.store.state.newMessage;
	},
	//设置最新消息
	set newMessage(data) {
		this.store.commit('setNewMessage', data);
	},
	//清空聊天记录
	removeNewMessage(data) {
		this.store.commit('removeNewMessage', data);
	},
	//重置最新消息
	forceSetNewMessage(data) {
		this.store.commit('forceSetNewMessage', this.createNewMessage(data));
	},
	//获取用户名
	get userName() {
		return uni.getStorageSync('userName');
	},
	//设置用户名
	set userName(data) {
		uni.setStorage({
			key: 'userName',
			data
		});
	},
	//生成新消息
	createNewMessage(d) {
		let other = d.type == 1 ? this.friends.find(f => f.Id == d.other) : this.groups.find(c => c.Id == d.other);
		if (!other) {
			return null;
		}
		let data = this.deepClone(d);
		data.time = data.time || this.serverTime;
		if (!(data.time instanceof Date)) {
			data.time = this.parseDate(data.time);
		}
		data.id = data.id || this.maxId;
		data.senderId = data.senderId || 0;
		data.msgcount = data.msgcount || 0;
		data.state = undefined === data.state ? 1 : data.state;
		data.obj = other;
		if (data.type == 2) {
			data.avatars = other.members.map(c => c.Avatar);
			data.groupname = other.GroupName;
		}
		return data;
	},
	//获取登录用户
	get loginUser() {
		return this.store.state.loginUser;
	},
	//设置登录用户
	set loginUser(data) {
		this.users = data;
		this.store.commit('setLoginUser', data);
	},
	//格式化文件大小
	formatFileSize(fileLength, upperCase) {
		if (fileLength < 1024) {
			fileLength = fileLength + 'b';
		} else if (fileLength < 1048576) {
			fileLength = (fileLength / 1024).toFixed(1) + 'kb';
		} else if (fileLength < 1073741824) {
			fileLength = (fileLength / 1048576).toFixed(1) + 'mb';
		} else {
			fileLength = (fileLength / 1073741824).toFixed(1) + 'gb';
		}
		if (upperCase) {
			fileLength = fileLength.toUpperCase();
		}
		return fileLength;
	},
	//设置用户信息
	set userInfo(data) {
		this.store.commit('setUserInfo', data);
	},
	//获取申请消息
	get applyMsgs() {
		return this.store.state.applyMsgs;
	},
	//设置申请消息
	set applyMsgs(data) {
		this.store.commit('setApplyMsg', data);
	},
	//申请总数
	get applyCount() {
		return this.applyMsgs.filter(c => c.Handled == 0).length;
	},
	//设置table栏的申请总数角标
	setTabApplyCount() {
		const count = this.applyCount;
		if (count == 0) {
			uni.removeTabBarBadge({
				index: 1
			});
		} else {
			uni.setTabBarBadge({
				index: 1,
				text: count > 99 ? '99+' : count + ''
			});
		}
	},
	//设置table栏的消息总数
	setTabMessageCount() {
		let msgs = this.newMessage;
		let count = msgs.length < 1 ? 0 : msgs.map(c => c.msgcount).reduce((total, count) => total + count);
		plus.runtime.setBadgeNumber(count);
		if (count == 0) {
			uni.removeTabBarBadge({
				index: 0
			});
		} else {
			uni.setTabBarBadge({
				index: 0,
				text: count > 99 ? '99+' : count + ''
			});
		}
	},
	//深拷贝
	deepClone(obj, newObj = {}) {
		for (let key in obj) {
			if (undefined == obj[key] || null == obj[key]) {
				newObj[key] = obj[key];
			} else if (obj[key] instanceof Date) {
				newObj[key] = obj[key];
			} else if (typeof obj[key] == 'object') {
				newObj[key] = (obj[key].constructor === Array) ? [] : {}
				this.deepClone(obj[key], newObj[key]);
			} else {
				newObj[key] = obj[key]
			}
		}
		return newObj;
	},
	//转换日期
	parseDate(time, switchTimeZone) {
		if (typeof time !== 'string' || !time) {
			return time;
		}
		let date = '';
		let milSeconds = '0';
		if (/^\d{4}\D\d{1,2}\D\d{1,2}$/.test(time)) {
			date = new Date(time);
		} else {
			date = time.split(':');
			if (date.length < 3) {
				return time;
			}
			if (date.length == 4) {
				milSeconds = date.pop();
				date = new Date(date.join(':'));
			}
			//如果毫秒是.的话
			else if (date.slice(-1)[0].indexOf('.') > 0) {
				let mils = date.slice(-1)[0].split('.');
				milSeconds = mils.pop();
				date.splice(2, 1, mils.shift());
				date = new Date(date.join(':'));
			}
		}
		if (switchTimeZone) {
			//如果不是中国时区则转为中国时区
			date = this.getChineseTime(date);
		}
		date.setMilliseconds(milSeconds.slice(0, 3));
		return date;
	},
	//设置公钥
	set publicKey(key) {
		this.store.commit('setPublicKey', key);
	},
	//获取公钥
	get publicKey() {
		return this.store.state.publicKey;
	},
	//获取中国时间
	getChineseTime(date = new Date()) {
		//如果不是中国时区则转为中国时区
		if (date.getTimezoneOffset() != -480) {
			date.setMinutes(date.getMinutes() + date.getTimezoneOffset() - 480);
		}
		return date;
	},
	// 获取是否连接
	get connected() {
		return this.store.state.connected;
	},
	//设置是否连接
	set connected(data) {
		this.store.commit('setConnected', data);
	},
	// 获取是否有更多的请求数据
	get hasMoreApply() {
		return this.data.hasMoreApply;
	},
	//设置是否有更多的请求数据
	set hasMoreApply(data) {
		this.data.hasMoreApply = data;
	},
	//添加新朋友
	addNewFriend(user) {
		this.friends = user;
		let msg = this.createNewMessage({
			other: user.Id,
			read: true,
			senderId: 0,
			type: 1,
			content: '我们已经是好友了，快来打招呼吧',
			messageType: 'System',
			avatar: user.Avatar,
			nickname: user.NickName
		});
		this.newMessage = msg;
		return msg;
	},
	//添加新群组
	addNewGroup(group, content) {
		this.groups = group;
		let msg = this.createNewMessage({
			other: group.Id,
			read: true,
			type: 2,
			content: content || '您已成功创建群组',
			messageType: 'System'
		});
		this.newMessage = msg;
		return msg;
	},
	//删除群组
	deleteGroup(groupId) {
		let index = this.groups.findIndex(c => c.Id == groupId);
		if (index >= 0) {
			this.groups.splice(index, 1);
		}
		index = this.newMessage.findIndex(c => c.other == groupId && c.type == 2);
		if (index >= 0) {
			this.newMessage.splice(index, 1);
		}
	},
	//删除群成员
	deleteGroupMember(group, userId) {
		if (typeof group == 'number') {
			group = this.groups.find(c => c.Id == group);
		}
		if (group) {
			let index = group.members.findIndex(c => c.Id == userId);
			index >= 0 && group.members.splice(index, 1);
			this.setGroupAvatars(group);
		}
	},
	//批量删除群成员
	deleteGroupMembers(group, userIds) {
		if (typeof group == 'number') {
			group = this.groups.find(c => c.Id == group);
		}
		if (group) {
			userIds.forEach(userId => {
				let index = group.members.findIndex(c => c.Id == userId);
				index >= 0 && group.members.splice(index, 1);
			});
			this.setGroupAvatars(group);
		}
	},
	//添加群成员
	addGroupMember(group, users) {
		if (typeof group == 'number') {
			group = this.groups.find(c => c.Id == group);
		}
		if (group) {
			if (!Array.isArray(users)) {
				users = [users];
			}
			this.mappingGroupMembers(users); //先映射关系
			//如果没有成员则直接将用户设置为成员
			if (!group.members) {
				group.members = users;
			} else {
				//如果有则将不存在的成员添加
				users.forEach(user => {
					//如果不存在则添加
					if (!group.members.find(c => c.Id == user.Id)) {
						group.members.push(user);
					}
				});
			}
			//最后再重新设置一下头像
			this.setGroupAvatars(group);
		}
	},
	//添加群聊消息
	addGroupMsg(msg) {
		let pages = getCurrentPages();
		while (pages.length > 0) {
			let page = pages.pop();
			if (page.route.indexOf('/chat') > 0) {
				if (page.$vm.type == 2 && page.$vm.user.Id == msg.other) {
					page.$vm.addMsg(msg);
				}
				return;
			}
		}
	},
	//视频预览
	videoPreview(list = [], current = '') {
		if (!list.length) {
			return;
		}
		this.data.videos = {
			list,
			current
		};
		uni.navigateTo({
			url: '/pages/search/preview'
		})
	},
	//设置群组标题
	setGroupTitle(id) {
		let pages = getCurrentPages();
		while (pages.length > 0) {
			let page = pages.pop();
			if (page.route.indexOf('groupInfo') > 0) {
				if (page.$vm.group.Id == id) {
					page.$vm.setTitle();
				}
				return;
			}
		}
	},
	//设置群组头像集
	setGroupAvatars(g) {
		if (typeof g === 'number') {
			g = this.groups.find(c => c.Id == id);
		}
		if (!g) {
			return;
		}
		let ownerIndex = g.members.findIndex(c => c.Id == g.Owner);
		//如果群主不是在第一则重新调整一下位置
		if (ownerIndex > 0) {
			g.members.unshift(g.members[ownerIndex]);
			g.members.splice(ownerIndex + 1, 1);
		}
		let msg = this.newMessage.find(c => c.other == g.Id && c.type == 2);
		if (msg) {
			let avatars = g.members.map(c => c.Avatar)
			// msg.avatars.splice(0, msg.avatars.length, ...avatars);
			msg.avatars = avatars;
		}
	},
	//根据用户ID设置群组头像
	setGroupAvatarsByUserId(userId) {
		let groups = this.groups;
		if (typeof userId === 'number' && userId != this.loginUser.Id) {
			groups = groups.filter(c => c.members.some(user => user.Id == userId));
		}
		groups.forEach(g => this.setGroupAvatars(g));
	},
	//设置未读数
	set unreadCount(data) {
		this.store.commit('setUnreadCount', data);
	},
	//获取新版本
	get newVersion() {
		return this.data.newVersion;
	},
	//设置新版本
	set newVersion(data) {
		this.data.newVersion = data;
	},
	//改变消息读取类型
	changeMsgReadType(msg) {
		if (msg && typeof msg.read === 'string') {
			msg.read = msg.read == 'true' || msg.read == 'True';
		}
	},
	//获取系统信息
	get sysInfo() {
		return this.data.sysInfo;
	},
	//设置系统信息
	set sysInfo(data) {
		this.data.sysInfo = data;
	},
	//点击加号菜单
	tapAddMenu({
		code
	}) {
		switch (code) {
			case 'group':
				uni.navigateTo({
					url: '/pages/group/create'
				})
				break;
			case 'scan':
				uni.$off('scanResult');
				uni.$on('scanResult', res => {
					uni.$off('scanResult');
					uni.navigateBack({
						animationDuration: 100,
						animationType: 'none'
					});
					if (res) {
						this.scanResult(res);
					}
				});
				uni.navigateTo({
					url: '/pages/message/scan',
					animationDuration: 200,
					animationType: 'zoom-fade-out'
				});
				break;
			case 'add':
				uni.navigateTo({
					url: '/pages/search/searchFriends'
				})
				break;
		}
	},
	//扫码结果
	scanResult(data) {
		if (typeof data.result === 'string') {
			data = JSON.parse(data.result);
		} else {
			data = data.result;
		}
		if (typeof data === 'string') {
			data = JSON.parse(data);
		}
		if (data.app != 'ycim') {
			this.showToast('非本应用二维码');
			return;
		}
		if (data.userId == this.loginUser.Id) {
			this.showToast('不能扫自己的二维码');
			return;
		}
		this.scanResultNavigator(data);
	},
	//扫描结果导航
	scanResultNavigator(data) {
		//好友
		if (data.type == 1) {
			if (data.userId == this.loginUser.Id) {
				return;
			}
			let f = this.friends.find(c => c.Id == data.userId);
			if (f) {
				uni.navigateTo({
					url: '/pages/contacts/friendInfo?id=' + data.userId
				});
			} else {
				uni.navigateTo({
					url: '/pages/contacts/addFriend?id=' + data.userId
				});
			}
		} else {
			let g = this.groups.find(c => c.Id == data.groupId);
			if (g) {
				uni.navigateTo({
					url: '/pages/message/chat?type=2&id=' + g.Id
				})
			} else {
				uni.navigateTo({
					url: '/pages/group/joinGroup?id=' + data.groupId
				})
			}
		}
	},
	//延迟执行
	//方法,名称,延迟毫秒
	execDelay(fn, name = 'default', milSeconds = 500) {
		let event = this.state.delayEvents[name];
		if (!event) {
			this.state.delayEvents[name] = event = {};
		}
		clearTimeout(event.id);
		event.id = setTimeout(fn, milSeconds);
	},
	//最大执行时间
	execMaxTime(fn, milSeconds) {
		return Promise.race([new Promise(res => {
			fn(res);
		}), new Promise((res, rej) => {
			setTimeout(() => {
				rej();
			}, milSeconds)
		})]);
	},
	//替换所有
	replaceAll(str, exp, newStr) {
		return str.replace(new RegExp(exp, "gm"), newStr);
	},
	//格式化
	format(result, args) {
		if (arguments.length < 1) {
			return result;
		}
		let data = [];
		if (Array.isArray(args)) {
			// 如果模板参数是对象
			data = args;
		} else {
			for (let k in arguments) {
				if (k != '0') {
					data.push(arguments[k]);
				}
			}
		}
		for (let key in data) {
			let value = data[key];
			if (undefined != value) {
				if (value.toString().indexOf('{') > -1) {
					result = result.replace('{' + key + '}', value);
				} else {
					result = this.replaceAll(result, "\\{" + key + "\\}", value);
				}
			}
		}
		return result;
	},
	//日期格式化
	formatDate(date, fmt = 'yyyy/MM/dd hh:mm:ss') {
		date = this.parseDate(date);
		var o = {
			"M+": date.getMonth() + 1, //月份 
			"d+": date.getDate(), //日 
			"h+": date.getHours(), //小时 
			"m+": date.getMinutes(), //分 
			"s+": date.getSeconds(), //秒 
			"q+": Math.floor((date.getMonth() + 3) / 3), //季度 
			"S": date.getMilliseconds() //毫秒 
		};
		if (/(y+)/.test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
		}
		for (var k in o) {
			if (new RegExp("(" + k + ")").test(fmt)) {
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
			}
		}
		return fmt;
	},
	//消息同步
	chatMessageAsync(other, type, data) {
		if (undefined === data) {
			return this.store.state.chatMessageAsync[`${other}_${type}`];
		} else {
			this.store.commit('chatMessageAsync', {
				other,
				type,
				data
			});
		}
	},
	//获取版本
	get version() {
		return this.store.state.version;
	},
	//设置版本
	set version(data) {
		this.store.commit('setVersion', data);
	},
	//清空所有数据
	clearAllData() {
		this.data.timeIds.forEach(id => {
			clearInterval(id);
		});
		plus.runtime.setBadgeNumber(0);
		this.store.commit('reset');
		this.data.hasMoreApply = null;
	}
}
